package com.fy56.platform.logistics.restful.api.controller.wx;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.Vip;
import com.fy56.platform.logistics.model.VipAppId;
import com.fy56.platform.logistics.model.VipOpenidRelate;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.CurrentUser;
import com.fy56.platform.logistics.service.wx.IVipService;
import com.fy56.platform.logistics.utils.IdWorkerTools;
import com.fy56.platform.logistics.utils.MD5Util;
import com.fy56.platform.logistics.utils.StringUtil;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 登陆RestController
 * @author  by li on 2018-02-01 16:05
 */
@Api(value = "Login", description = "注册登录", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private IVipService vipService;

	private static Logger log = Logger.getLogger(LoginController.class);

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ApiOperation(value = "注册")
	public ResponseEntity register(@RequestParam String data) {
		log.info("新用户注册----参数：" + data);
        String openId = JSON.parseObject(data).getString("openid");
        if("null".equals(openId)){
			return new ResponseEntity<>(ResultModel.error(ResultStatus.OPEN_ID_ERR), HttpStatus.OK);
		}
        Vip regVipInfo =  JSON.parseObject(data).toJavaObject(Vip.class);
        String userName = regVipInfo.getMobile();
        String password = regVipInfo.getPassword();
		Vip model = new Vip();
		model.setMobile(userName);
		Vip user = vipService.get(model);
		if (user != null) {
            return new ResponseEntity<>(ResultModel.error(ResultStatus.EXIST_ERR), HttpStatus.OK);
		}else{
            regVipInfo.setId(Long.parseLong(IdWorkerTools.getInstance().getId()));
            regVipInfo.setPassword(MD5Util.getMD5Code(password).toUpperCase());
//            regVipInfo.setOpenId(openId);
			regVipInfo.setCreateTime(new Date());
            vipService.insert(regVipInfo);
		}
        return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity login(@RequestParam String username, @RequestParam String password,@RequestParam String openid) {

		//参数验证
		Assert.notNull(username, "用户名不能为空");
		Assert.notNull(password, "密码不能为空");
		Assert.notNull(openid, "openid不能为空");

		//根据参数获取数据库中的用户
		Vip model = new Vip();
		model.setMobile(username);
		Vip user = vipService.get(model);

		//openid
		if (openid == null || "null".equals(openid)) {
			return new ResponseEntity<>(ResultModel.error(ResultStatus.OPEN_ID_ERR), HttpStatus.OK);
		}

		//未注册
		if (user == null) {
			return new ResponseEntity<>(ResultModel.error(ResultStatus.USER_NOT_FOUND), HttpStatus.OK);
		}

		//密码错误
		if(!user.getPassword().equals(MD5Util.getMD5Code(password).toUpperCase())){
			return new ResponseEntity<>(ResultModel.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR), HttpStatus.OK);
		}

		//判断是否登录过,若已登录过，直接返回
		VipOpenidRelate searchModel = new VipOpenidRelate();
		searchModel.setVipMemberId(user.getId());
		searchModel.setOpenid(openid);
		if(vipService.existByVip(searchModel)){
			return new ResponseEntity<>(ResultModel.ok(user), HttpStatus.OK);
		}

		//生成一个token，保存用户登录状态
		/*if(StringUtil.isNotEmpty(user.getOpenId()) && !openid.equals(user.getOpenId())){
			return new ResponseEntity<>(ResultModel.error(ResultStatus.WX_IS_EXIST), HttpStatus.OK);
		}*/

		searchModel.setCreateTime(new Date());
		vipService.saveVipOpenid(searchModel);
		user.setOpenId(openid);
		return new ResponseEntity<>(ResultModel.ok(user), HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.DELETE)
	@Authorization
	@ApiOperation(value = "退出登录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
	})
	public ResponseEntity<ResultModel> logout(@CurrentUser Vip user) {
		return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
	}

    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ResponseEntity logout(@RequestParam String openId,@RequestParam String vipMemberId) {
		VipOpenidRelate model = new VipOpenidRelate();
		model.setOpenid(openId);
		model.setVipMemberId(Long.valueOf(vipMemberId));
		vipService.removeOpenid(model);
        return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
    }

	@ApiOperation(value = "无密码登录")
	@RequestMapping(value = "/loginNotPassWord", method = RequestMethod.POST)
	public ResponseEntity loginNotPassWord(@RequestParam String username,
										   @RequestParam String unionId,
										   @RequestParam String openid,
										   @RequestParam(required=false) String name,
										   @RequestParam(required=false) String city,
										   @RequestParam(required=false) String province,
										   @RequestParam(required=false) String address,
										   @RequestParam(required=false) String code) {

		//参数验证
		Assert.notNull(username, "用户名不能为空");
		Assert.notNull(unionId, "用户id不能为空");
		Assert.notNull(openid, "openid不能为空");

		//根据参数获取数据库中的用户
		Vip model = new Vip();
		model.setMobile(username);
		Vip user = vipService.get(model);

		//openid
		if (openid == null || "null".equals(openid)) {
			return new ResponseEntity<>(ResultModel.error(ResultStatus.OPEN_ID_ERR), HttpStatus.OK);
		}

		//未注册 自动注册
		if (user == null) {
			Vip regVipInfo =new Vip();
			regVipInfo.setMobile(username);
			regVipInfo.setName(name);
			regVipInfo.setVipNo(name);
			regVipInfo.setSourceFlag("小程序");
			regVipInfo.setCity(city);
			regVipInfo.setProvince(province);
			regVipInfo.setAddress(address);
			regVipInfo.setCode(code);
			regVipInfo.setId(Long.parseLong(IdWorkerTools.getInstance().getId()));
			regVipInfo.setPassword(MD5Util.getMD5Code("666666").toUpperCase());
//            regVipInfo.setOpenId(openId);
			regVipInfo.setCreateTime(new Date());
			vipService.insert(regVipInfo);
			user = vipService.get(model);
		}
		try{
			VipAppId vipAppId = new VipAppId();
			vipAppId.setCode(code);
			vipAppId.setVipMemberId(user.getId());
			vipAppId.setCreateTime(new Date());
			vipService.saveVipAppId(vipAppId);
		}catch (Exception e){

		}



		//判断是否登录过,若已登录过，直接返回
		VipOpenidRelate searchModel = new VipOpenidRelate();
		searchModel.setVipMemberId(user.getId());
		searchModel.setOpenid(openid);
		if(vipService.existByVip(searchModel)){
			return new ResponseEntity<>(ResultModel.ok(user), HttpStatus.OK);
		}

		//生成一个token，保存用户登录状态
		/*if(StringUtil.isNotEmpty(user.getOpenId()) && !openid.equals(user.getOpenId())){
			return new ResponseEntity<>(ResultModel.error(ResultStatus.WX_IS_EXIST), HttpStatus.OK);
		}*/

		searchModel.setCreateTime(new Date());
		vipService.saveVipOpenid(searchModel);
		user.setOpenId(openid);
		return new ResponseEntity<>(ResultModel.ok(user), HttpStatus.OK);
	}

}